package com.gmail.hy87cn.hellohi.server;

import java.util.ArrayList;

import com.gmail.hy87cn.hellohi.shared.ERoomState;
import com.gmail.hy87cn.hellohi.shared.HiMessage;
import com.gmail.hy87cn.hellohi.shared.HiRoom;
import com.gmail.hy87cn.hellohi.shared.HiUser;

/**
 * @author HeYi
 * 
 */
public class HiRoomPackage {
	private HiRoom room;

	public HiRoomPackage() {
		room = new HiRoom();
		room.setCapacity(2);
		room.setMessageList(new ArrayList<HiMessage>());
		room.setUserList(new ArrayList<HiUser>(2));
		room.setState(ERoomState.Open);
	}

	public HiRoom getRoom() {
		return room;
	}

	public void addUser(HiUserPackage userPackage) {
		if (room.getState() == ERoomState.Open
				&& !room.getUserList().contains(userPackage.getUser())) {
			room.getUserList().add(userPackage.getUser());
			if (room.getUserList().size() == room.getCapacity()) {
				room.setState(ERoomState.Locked);
			}
		}
	}

	public void removeUser(HiUserPackage userPackage) {
		ArrayList<HiUser> userList = room.getUserList();
		userList.remove(userPackage.getUser());
		if (userList.size() == 1) {
			int id = userList.get(0).getId();
			HiUserManager.sGetInstance().getUser(id).setRoomPackage(null);
		}
	}

	public void addMessage(HiMessage message) {
		room.getMessageList().add(message);
	}

	public HiMessage[] getMessages(int token, int lastIndex) {
		ArrayList<HiMessage> messages = new ArrayList<HiMessage>();
		ArrayList<HiMessage> messageList = room.getMessageList();
		for (int i = lastIndex; i < messageList.size(); i++) {
			HiMessage message = messageList.get(i);
			if (message.getUserId() != token) {
				messages.add(message);
			}
		}
		HiMessage[] result = new HiMessage[messages.size()];
		messages.toArray(result);
		return result;
	}
}
